﻿HmJS.$Import('util.IdleTimer');
//HmJS.$Import('core.domready');

HmJS.register('demo.module.util.idletimer', function ($ns) {
	var that = {};

	var IdleTimer = $ns.util.IdleTimer;

	var idleDemo = {
		logoutHeader: {
			counter: 30,

			start: function () {
				$('logoutHeader').removeClass('hidden');
				idleDemo.logoutHeader.timer = idleDemo.logoutHeader.countdown.periodical(1000);
			},

			stop: function () {
				clearInterval(idleDemo.logoutHeader.timer);
				$('logoutHeader').addClass('hidden');
				idleDemo.logoutHeader.counter = 30;
				$('logoutTime').set('text', 30);
				$('inactivity').removeClass('hidden');
				$('doLogout').addClass('hidden');
			},

			countdown: function () {
				if (idleDemo.logoutHeader.counter-- == 1) {
					return idleDemo.logoutHeader.logout();
				}
				$('logoutTime').set('text', idleDemo.logoutHeader.counter);
			},

			logout: function () {
				clearInterval(idleDemo.logoutHeader.timer);
				$$('#inactivity, #doLogout').toggleClass('hidden');
			}
		}
	};

	that.todo = function () {
		// Add event do window. If you want to set a non-default timeout, you need to do:
		// new IdleTimer(window, { timeout: ms }).start();
		// "ms" means the number of milliseconds before you concider the user as idle
		window.idleTimer = new IdleTimer(document, { timeout: 5000 }).start().addEvents({
			'idle': function () { $('box5s').addClass('idle'); $('statusText5s').set('text', 'Idle!'); },
			'active': function () { $('box5s').removeClass('idle'); $('statusText5s').set('text', 'Active!'); }
		});

		// Using a bit different syntax for this one: setting a custom timeout (10 seconds)
		// Also, don't bother listening to keyboard events as they will not fire on a div
		var spec = $('special').set('idle', { timeout: 10000, events: ['mousemove', 'mousewheel', 'mousedown'] }).addEvents({
			'idle': function () { $('special').addClass('idle'); $('specialStatus').set('text', 'Idle!'); },
			'active': function () { $('special').removeClass('idle'); $('specialStatus').set('text', 'Active!'); }
		});
		idleDemo.specialTimer = spec.get('idle');

		// And yet another way of doing it...
		idleDemo.longTimer = new IdleTimer(document, { timeout: 30000 }).start().addEvents({
			'idle': function () { $('box30s').addClass('idle'); $('statusText30s').set('text', 'Idle!'); idleDemo.logoutHeader.start(); },
			'active': function () { $('box30s').removeClass('idle'); $('statusText30s').set('text', 'Active!'); idleDemo.logoutHeader.stop(); }
		});

		// Update the idle time every second
		(function () {
			$('idleTime5s').set('text', window.idleTimer.getIdleTime() + ' ms');
			$('idleTime30s').set('text', idleDemo.longTimer.getIdleTime() + ' ms');
			$('specialTime').set('text', idleDemo.specialTimer.getIdleTime() + ' ms');
		}).periodical(1000);
	};

	return that;
});
